// ==================== 渲染服务 ====================
// 职责：处理Canvas渲染相关的逻辑
// 遵循单一职责原则，专注于渲染功能

import { computed } from 'vue'
import { usePlacementStore } from '@/stores'

export function useRender(ctx, viewport, layers, selectedObjects, hoveredObject, canvasSettings) {
  const placementStore = usePlacementStore()
  
  // ==================== 渲染工具函数 ====================
  /**
   * 渲染背景
   */
  const renderBackground = () => {
    if (!ctx.value) return
    
    ctx.value.fillStyle = canvasSettings.value.backgroundColor
    ctx.value.fillRect(0, 0, ctx.value.canvas.width, ctx.value.canvas.height)
  }

  /**
   * 渲染网格
   * 修复：网格应该在视口变换后渲染，使用世界坐标
   */
  const renderGrid = () => {
    if (!ctx.value || !canvasSettings.value.showGrid) return
    
    const gridSize = 20
    const step = gridSize // 网格大小固定，不受缩放影响
    
    ctx.value.strokeStyle = canvasSettings.value.gridColor
    ctx.value.lineWidth = 1 / viewport.value.zoom // 线条宽度随缩放调整
    
    // 计算网格在世界坐标系中的范围
    const canvasWidth = ctx.value.canvas.width / viewport.value.zoom
    const canvasHeight = ctx.value.canvas.height / viewport.value.zoom
    
    // 计算网格起始位置（对齐到网格）
    const startX = Math.floor(-viewport.value.x / step) * step
    const startY = Math.floor(-viewport.value.y / step) * step
    
    // 绘制垂直线
    for (let x = startX; x <= startX + canvasWidth + step; x += step) {
      ctx.value.beginPath()
      ctx.value.moveTo(x, -viewport.value.y)
      ctx.value.lineTo(x, -viewport.value.y + canvasHeight)
      ctx.value.stroke()
    }
    
    // 绘制水平线
    for (let y = startY; y <= startY + canvasHeight + step; y += step) {
      ctx.value.beginPath()
      ctx.value.moveTo(-viewport.value.x, y)
      ctx.value.lineTo(-viewport.value.x + canvasWidth, y)
      ctx.value.stroke()
    }
  }

  /**
   * 渲染单个对象
   */
  const renderObject = (obj) => {
    if (!ctx.value) return
    
    ctx.value.save()
    
    // 应用图层透明度
    ctx.value.globalAlpha = obj.layerOpacity || 1
    
    ctx.value.translate(obj.x + obj.width / 2, obj.y + obj.height / 2)
    ctx.value.rotate(obj.rotation * Math.PI / 180)
    
    // 绘制对象
    ctx.value.fillStyle = obj.color
    ctx.value.fillRect(-obj.width / 2, -obj.height / 2, obj.width, obj.height)
    
    // 绘制对象名称
    if (canvasSettings.value.showLabels) {
      ctx.value.fillStyle = '#000000'
      ctx.value.font = '12px Arial'
      ctx.value.textAlign = 'center'
      ctx.value.fillText(obj.type, 0, 0)
    }
    
    // 选中状态
    if (selectedObjects.value.find(selected => selected.id === obj.id)) {
      ctx.value.strokeStyle = '#3B82F6'
      ctx.value.lineWidth = 2
      ctx.value.strokeRect(-obj.width / 2, -obj.height / 2, obj.width, obj.height)
      
      // 绘制控制点
      drawControlPoints(obj)
    }
    
    // 悬停状态
    if (hoveredObject.value && hoveredObject.value.id === obj.id) {
      ctx.value.strokeStyle = '#EF4444'
      ctx.value.lineWidth = 1
      ctx.value.strokeRect(-obj.width / 2, -obj.height / 2, obj.width, obj.height)
    }
    
    ctx.value.restore()
  }

  /**
   * 绘制控制点
   */
  const drawControlPoints = (object) => {
    if (!ctx.value) return
    
    // 角点控制点（用于缩放）
    const cornerPoints = [
      { x: -object.width / 2, y: -object.height / 2, type: 'nw' }, // 左上
      { x: object.width / 2, y: -object.height / 2, type: 'ne' },  // 右上
      { x: object.width / 2, y: object.height / 2, type: 'se' },   // 右下
      { x: -object.width / 2, y: object.height / 2, type: 'sw' }   // 左下
    ]
    
    // 边中点控制点（用于单方向缩放）
    const edgePoints = [
      { x: 0, y: -object.height / 2, type: 'n' },  // 上
      { x: object.width / 2, y: 0, type: 'e' },    // 右
      { x: 0, y: object.height / 2, type: 's' },   // 下
      { x: -object.width / 2, y: 0, type: 'w' }    // 左
    ]
    
    // 旋转控制点（在对象上方）
    const rotationPoint = {
      x: 0,
      y: -object.height / 2 - 20, // 距离对象顶部20像素
      type: 'rotation'
    }
    
    // 绘制角点控制点（方形）
    cornerPoints.forEach(point => {
      ctx.value.fillStyle = '#ffffff'
      ctx.value.strokeStyle = '#3B82F6'
      ctx.value.lineWidth = 1
      ctx.value.fillRect(point.x - 4, point.y - 4, 8, 8)
      ctx.value.strokeRect(point.x - 4, point.y - 4, 8, 8)
    })
    
    // 绘制边中点控制点（圆形）
    edgePoints.forEach(point => {
      ctx.value.fillStyle = '#ffffff'
      ctx.value.strokeStyle = '#3B82F6'
      ctx.value.lineWidth = 1
      ctx.value.beginPath()
      ctx.value.arc(point.x, point.y, 4, 0, 2 * Math.PI)
      ctx.value.fill()
      ctx.value.stroke()
    })
    
    // 绘制旋转控制点（圆形箭头）
    ctx.value.fillStyle = '#ffffff'
    ctx.value.strokeStyle = '#3B82F6'
    ctx.value.lineWidth = 1
    ctx.value.beginPath()
    ctx.value.arc(rotationPoint.x, rotationPoint.y, 6, 0, 2 * Math.PI)
    ctx.value.fill()
    ctx.value.stroke()
    
    // 绘制旋转箭头
    ctx.value.strokeStyle = '#3B82F6'
    ctx.value.lineWidth = 2
    ctx.value.beginPath()
    // 绘制弧形箭头
    ctx.value.arc(rotationPoint.x, rotationPoint.y, 8, -Math.PI/4, Math.PI/4)
    ctx.value.stroke()
    
    // 绘制箭头头部
    ctx.value.beginPath()
    ctx.value.moveTo(rotationPoint.x + 6, rotationPoint.y - 6)
    ctx.value.lineTo(rotationPoint.x + 10, rotationPoint.y - 2)
    ctx.value.lineTo(rotationPoint.x + 6, rotationPoint.y + 2)
    ctx.value.closePath()
    ctx.value.fill()
  }

  /**
   * 渲染选择框
   */
  const renderSelectionBox = (selectionBox) => {
    if (!ctx.value || !selectionBox.value.visible) return
    
    const left = Math.min(selectionBox.value.start.x, selectionBox.value.end.x)
    const top = Math.min(selectionBox.value.start.y, selectionBox.value.end.y)
    const width = Math.abs(selectionBox.value.end.x - selectionBox.value.start.x)
    const height = Math.abs(selectionBox.value.end.y - selectionBox.value.start.y)
    
    ctx.value.strokeStyle = '#3B82F6'
    ctx.value.lineWidth = 1
    ctx.value.setLineDash([5, 5])
    ctx.value.strokeRect(left, top, width, height)
    ctx.value.setLineDash([])
    
    ctx.value.fillStyle = 'rgba(59, 130, 246, 0.1)'
    ctx.value.fillRect(left, top, width, height)
  }

  /**
   * 渲染坐标信息
   */
  const renderCoordinateInfo = (mousePosition) => {
    if (!ctx.value) return
    
    const x = mousePosition.value.x
    const y = mousePosition.value.y
    const zoom = Math.round(viewport.value.zoom * 100)
    
    ctx.value.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.value.fillRect(10, 10, 120, 60)
    
    ctx.value.fillStyle = '#000000'
    ctx.value.font = '12px Arial'
    ctx.value.textAlign = 'left'
    ctx.value.fillText(`X: ${Math.round(x)}px`, 15, 30)
    ctx.value.fillText(`Y: ${Math.round(y)}px`, 15, 45)
    ctx.value.fillText(`缩放: ${zoom}%`, 15, 60)
  }

  /**
   * 渲染导入的图片
   * @param {Object} object - 图片对象
   */
  const renderImportedImage = (object) => {
    if (!ctx.value) return
    
    // 兼容：优先使用缓存的 Image，其次尝试使用 imageUrl 懒加载
    let img = object.image || object._loadedImage
    if (!img && object.imageUrl) {
      const preload = new Image()
      preload.onload = () => {
        object._loadedImage = preload
      }
      preload.src = object.imageUrl
      img = preload
    }

    ctx.value.save()
    ctx.value.globalAlpha = object.layerOpacity || 1
    ctx.value.translate(object.x + object.width / 2, object.y + object.height / 2)
    ctx.value.rotate(object.rotation * Math.PI / 180)
    
    if (img) {
      ctx.value.drawImage(img, -object.width / 2, -object.height / 2, object.width, object.height)
    } else {
      // 图片未就绪时画占位
      ctx.value.fillStyle = 'rgba(0,0,0,0.05)'
      ctx.value.strokeStyle = '#9CA3AF'
      ctx.value.lineWidth = 1
      ctx.value.fillRect(-object.width / 2, -object.height / 2, object.width, object.height)
      ctx.value.strokeRect(-object.width / 2, -object.height / 2, object.width, object.height)
    }

    // 选中状态
    if (selectedObjects.value.find(selected => selected.id === object.id)) {
      ctx.value.strokeStyle = '#3B82F6'
      ctx.value.lineWidth = 2
      ctx.value.strokeRect(-object.width / 2, -object.height / 2, object.width, object.height)
      drawControlPoints(object)
    }
    
    // 悬停状态
    if (hoveredObject.value && hoveredObject.value.id === object.id) {
      ctx.value.strokeStyle = '#EF4444'
      ctx.value.lineWidth = 1
      ctx.value.strokeRect(-object.width / 2, -object.height / 2, object.width, object.height)
    }

    ctx.value.restore()
  }

  /**
   * 渲染放置中的预览
   */
  const renderPlacementPreview = () => {
    if (!ctx.value) return
    if (!placementStore.isPlacing || !placementStore.item) return

    const { x, y } = placementStore.position
    const { width, height } = placementStore.size

    // 预加载/缓存图片
    let img = placementStore.image
    if (!img && placementStore.item?.thumbnail) {
      const preload = new Image()
      preload.onload = () => {
        placementStore.image = preload
      }
      preload.src = placementStore.item.thumbnail
      img = preload
    }

    ctx.value.save()
    ctx.value.globalAlpha = 0.8
    if (img) {
      ctx.value.drawImage(img, x - width / 2, y - height / 2, width, height)
    } else {
      // 图片未就绪时，画占位框
      ctx.value.fillStyle = 'rgba(59,130,246,0.15)'
      ctx.value.strokeStyle = '#3B82F6'
      ctx.value.lineWidth = 1
      ctx.value.fillRect(x - width / 2, y - height / 2, width, height)
      ctx.value.strokeRect(x - width / 2, y - height / 2, width, height)
    }
    ctx.value.restore()
  }


  // ==================== 主要渲染函数 ====================
  /**
   * 渲染所有图层
   * 职责：按zIndex排序渲染所有可见对象
   */
  const renderAllLayers = () => {
    if (!ctx.value) return
    
    // 获取所有可见图层的对象，按zIndex排序
    const allObjects = []
    
    layers.value.forEach(layer => {
      if (layer.visible) {
        layer.objects.forEach(obj => {
          allObjects.push({
            ...obj,
            layerOpacity: layer.opacity,
            layerColor: layer.color
          })
        })
      }
    })
    
    // 按zIndex排序实现堆叠
    allObjects.sort((a, b) => {
      // 首先按zIndex排序
      if (a.zIndex !== b.zIndex) {
        return a.zIndex - b.zIndex
      }
      // 然后按图层顺序排序
      const layerA = layers.value.find(l => l.id === a.layerId)
      const layerB = layers.value.find(l => l.id === b.layerId)
      return (layerA?.order || 0) - (layerB?.order || 0)
    })
    
    // 渲染背景
    renderBackground()
    
    // 渲染网格
    renderGrid()
    
    // 渲染所有对象
    allObjects.forEach(obj => {
      if (obj.type === 'image') {
        renderImportedImage(obj)
      } else {
        renderObject(obj)
      }
    })

    // 渲染放置预览（位于对象之上）
    renderPlacementPreview()
  }

  /**
   * 渲染UI元素
   */
  const renderUI = (selectionBox, mousePosition) => {
    if (!ctx.value) return
    
    // 绘制选择框
    renderSelectionBox(selectionBox)
    
    // 绘制坐标信息
    renderCoordinateInfo(mousePosition)
  }

  /**
   * 完整渲染流程
   * 修复：正确的渲染顺序和坐标变换
   */
  const render = (selectionBox, mousePosition) => {
    if (!ctx.value) return
    
    // 清空画布
    ctx.value.clearRect(0, 0, ctx.value.canvas.width, ctx.value.canvas.height)
    
    // 应用视口变换
    ctx.value.save()
    ctx.value.translate(viewport.value.x, viewport.value.y)
    ctx.value.scale(viewport.value.zoom, viewport.value.zoom)
    ctx.value.rotate(viewport.value.rotation)
    
    // 渲染所有图层（包括网格）
    renderAllLayers()
    
    // 恢复变换
    ctx.value.restore()
    
    // 渲染UI元素（不受视口变换影响）
    renderUI(selectionBox, mousePosition)
  }

  // ==================== 导出接口 ====================
  return {
    // 主要渲染函数
    render,
    renderAllLayers,
    renderUI,
    
    // 工具函数
    renderBackground,
    renderGrid,
    renderObject,
    renderSelectionBox,
    renderCoordinateInfo,
    drawControlPoints
  }
}
